import AccountServices, { AccountListSearchParams } from '@/api/services/accountServices.ts';
import { useUserId } from '@/store/userStore.ts';
import ITable, { ITableProps, ITableRef } from '@/components/Table';
import { RoleInfo, UserInfo } from '#/entity.ts';
import { App, Button, SelectProps, Space, Switch, Tag, Tooltip } from 'antd';
import { FormFieldType } from '@ycx/ui';
import { useMutation, useQuery } from '@tanstack/react-query';
import RoleServices from '@/api/services/roleServices.ts';
import { useRef } from 'react';
import EditUserModal, {
  EditUserModalRef,
} from '@/pages/system/accountManagement/components/EditUserModal.tsx';
import { DefaultPwd } from '#/enmu.ts';
import DeleteButton from '@/components/DeleteButton';
import { Result } from '#/api.ts';
import { useCatch } from '@/hooks';
import PermissionGuard from '@/components/PermissionGuard';
import { canIUse } from '@/utils';

const AccountManagement = () => {
  const { message } = App.useApp();
  const id = useUserId();
  const catchFn = useCatch();

  const modalRef = useRef<EditUserModalRef>(null);
  const tableRef = useRef<ITableRef>(null);
  const modalCallback = () => tableRef.current?.refetch();

  const { data } = useQuery<Result<RoleInfo[]>, Error, SelectProps['options']>({
    queryKey: ['role-list', id],
    queryFn: () => catchFn(() => RoleServices.getRolesByUserId({ userId: id! })),
    select: ({ data }) => data.map((i) => ({ label: i.roleName, value: i.id })),
  });

  const { mutate: setUserBlock } = useMutation({
    mutationFn: AccountServices.update,
    onSuccess: () => tableRef.current?.refetch(),
    onError: (error) => {
      message.error(error.message);
    },
  });

  const { mutate: remove } = useMutation({
    mutationFn: AccountServices.remove,
    onSuccess: () => {
      message.success('用户删除成功');
      tableRef.current?.refetch();
    },
  });

  const { mutate: resetPwd } = useMutation({
    mutationFn: AccountServices.resetPwd,
    onSuccess: () => {
      message.success({
        content: `用户密码重置成功，初始密码为「${DefaultPwd.Gov}」`,
      });
    },
  });

  const tableProps: ITableProps<UserInfo, AccountListSearchParams> = {
    api: {
      fn: async (params) => {
        const { data, total } = await AccountServices.getAccountList({
          ...params,
          parentId: id!,
        });
        return {
          data,
          total: total ?? 0,
        };
      },
      key: ['account-list'],
    },
    columns: [
      {
        fixed: 'left',
        title: '账号',
        dataIndex: 'userName',
        ellipsis: true,
        width: 100,
      },
      {
        title: '联系方式',
        dataIndex: 'phone',
        width: 200,
        ellipsis: true,
        render: (value) => {
          return <Tooltip title={value}>{value}</Tooltip>;
        },
      },
      {
        title: '真实姓名',
        dataIndex: 'realName',
        width: 200,
        ellipsis: true,
        render: (value) => {
          return <Tooltip title={value}>{value}</Tooltip>;
        },
      },
      {
        title: '角色',
        dataIndex: 'roleList',
        width: 200,
        render: (value: RoleInfo[] | undefined) => {
          return <>{value?.map((i) => <Tag key={i.id}>{i.roleName}</Tag>)}</>;
        },
      },
      {
        title: '启用状态',
        dataIndex: 'userBlock',
        width: 100,
        render: (value: boolean, record) => {
          return (
            <Switch
              disabled={!canIUse(['ACCOUNT_UPDATE'])}
              checked={!value}
              checkedChildren="开"
              unCheckedChildren="关"
              onChange={(val) => {
                setUserBlock({ id: record.id, userBlock: !val });
              }}
            />
          );
        },
      },
      {
        fixed: 'right',
        title: '操作',
        dataIndex: 'operation',
        width: 180,
        render: (_value, record) => {
          return (
            <Space size={0}>
              <PermissionGuard permissions={['ACCOUNT_UPDATE', 'ACCOUNT_ASSIGN_ROLE']}>
                <Button size="small" type="link" onClick={() => modalRef.current?.open(record.id)}>
                  编辑
                </Button>
              </PermissionGuard>

              <PermissionGuard permissions={['ACCOUNT_DELETE']}>
                <DeleteButton onConfirm={() => remove(record.id)}>删除</DeleteButton>
              </PermissionGuard>

              <PermissionGuard permissions={['ACCOUNT_UPDATE']}>
                <Button size="small" type="link" onClick={() => resetPwd(record.id.toString())}>
                  重置密码
                </Button>
              </PermissionGuard>
            </Space>
          );
        },
      },
    ],
    fields: [
      {
        name: 'realName',
        type: FormFieldType.Input,
        label: '真实姓名',
      },
      {
        name: 'userName',
        type: FormFieldType.Input,
        label: '账号',
      },
      {
        name: 'phone',
        type: FormFieldType.Input,
        label: '联系方式',
      },
      {
        name: 'roleId',
        type: FormFieldType.Select,
        label: '角色',
        fieldProps: {
          options: data ?? [],
        },
      },
    ],
    extra: (
      <Button type="primary" onClick={() => modalRef.current?.open()}>
        新增用户
      </Button>
    ),
    rowKey: 'id',
  };

  return (
    <>
      <ITable<UserInfo, AccountListSearchParams> {...tableProps} ref={tableRef} />
      <EditUserModal ref={modalRef} callback={modalCallback} />
    </>
  );
};

export default AccountManagement;
